<script setup>
import { ref, onMounted } from 'vue';
import { List, Cell, Button, Search, showToast, DatePicker, Popup, Field, DropdownMenu, DropdownItem, Icon } from 'vant';
import { useRoute, useRouter } from 'vue-router';
import {
  getProcessInstancePage,
  reRunProcessInstance,
  pauseProcessInstance,
  stopProcessInstance,
  deleteProcessInstance
} from '@/api/dolphin.js';

const items = ref([]);
const loading = ref(false);
const finished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const searchVal = ref('');
const stateType = ref('');
const startDate = ref('');
const endDate = ref('');
const refreshing = ref(false);

const route = useRoute();
const router = useRouter();
const clusterId = ref(route.params.clusterId || 'default-cluster-id');
const projectCode = ref(Number(route.params.projectCode) || 12345);

// 状态选项
const stateOptions = [
  { text: '全部', value: '' },
  { text: '正在运行', value: 'RUNNING_EXECUTION' },
  { text: '成功', value: 'SUCCESS' },
  { text: '失败', value: 'FAILURE' },
  { text: '停止', value: 'STOP' },
  { text: '暂停', value: 'PAUSE' }
];

// 获取状态显示文本
const getStateText = (value) => {
  const option = stateOptions.find(opt => opt.value === value);
  return option ? option.text : '全部';
};

// 格式化日期
const formatDate = (date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 重置搜索条件
const onReset = () => {
  searchVal.value = '';
  stateType.value = '';
  startDate.value = '';
  endDate.value = '';
  onSearch();
};

// 初始化搜索结果
onMounted(() => {
  console.log('Component mounted');
  console.log('Cluster ID:', clusterId.value);
  console.log('Project Code:', projectCode.value);
  onSearch();
});

const onSearch = async () => {
  try {
    // 重置所有状态
    currentPage.value = 1;
    items.value = [];
    loading.value = true;
    finished.value = false;

    const response = await getProcessInstancePage(
      clusterId.value, 
      projectCode.value, 
      undefined, 
      currentPage.value, 
      pageSize.value, 
      searchVal.value,
      stateType.value,
      startDate.value,
      endDate.value
    );
    
    if (response?.data?.records) {
      items.value = response.data.records;
      
      // 检查是否还有更多数据
      if (response.data.records.length < pageSize.value || 
          response.data.currentPage >= response.data.totalPages) {
        finished.value = true;
      } else {
        currentPage.value++;
      }
    } else {
      items.value = [];
      finished.value = true;
    }
  } catch (error) {
    console.error('搜索工作流实例失败:', error);
    showToast('搜索工作流实例失败');
    finished.value = true;
  } finally {
    loading.value = false;
  }
};

const onLoad = async () => {
  if (finished.value) return;

  try {
    loading.value = true;
    console.log('加载第', currentPage.value, '页');

    const response = await getProcessInstancePage(
      clusterId.value, 
      projectCode.value, 
      undefined, 
      currentPage.value, 
      pageSize.value, 
      searchVal.value,
      stateType.value,
      startDate.value,
      endDate.value
    );
    
    console.log('加载更多响应:', response);

    if (response?.data?.records) {
      items.value.push(...response.data.records);
      
      if (response.data.records.length < pageSize.value || 
          response.data.currentPage >= response.data.totalPages) {
        finished.value = true;
      } else {
        currentPage.value++;
      }
    } else {
      finished.value = true;
    }
  } catch (error) {
    console.error('加载更多失败:', error);
    showToast('加载更多失败');
    finished.value = true;
  } finally {
    loading.value = false;
  }
};

// 添加状态判断方法
const isRunning = (state) => state === 'RUNNING_EXECUTION';
const isPaused = (state) => state === 'PAUSE';
const isStopped = (state) => state === 'STOP';
const isSuccess = (state) => state === 'SUCCESS';
const isFailure = (state) => state === 'FAILURE';
const isFinished = (state) => isSuccess(state) || isFailure(state) || isStopped(state);

// 按钮可用性判断
const canReRun = (state) => {
  // 运行中和暂停状态不能重跑
  return !isRunning(state) && !isPaused(state);
};

const canPause = (state) => {
  // 只有运行中状态可以暂停
  return isRunning(state);
};

const canStop = (state) => {
  // 运行中和暂停状态可以停止
  return isRunning(state) || isPaused(state);
};

const canDelete = (state) => {
  // 运行中和暂停状态不能删除
  return !isRunning(state) && !isPaused(state);
};

// 获取按钮禁用提示文本
const getButtonDisabledTip = (action, state) => {
  switch (action) {
    case 'rerun':
      if (isRunning(state)) return '运行中不能重新运行';
      if (isPaused(state)) return '暂停状态不能重新运行';
      return '';
    case 'pause':
      if (isFinished(state)) return '已完成的工作流不能暂停';
      if (isPaused(state)) return '已经是暂停状态';
      if (!isRunning(state)) return '只有运行中的工作流可以暂停';
      return '';
    case 'stop':
      if (isFinished(state)) return '已完成的工作流不能停止';
      if (!isRunning(state) && !isPaused(state)) return '只有运行中或暂停状态可以停止';
      return '';
    case 'delete':
      if (isRunning(state)) return '运行中的工作流不能删除';
      if (isPaused(state)) return '暂停状态不能删除';
      return '';
    default:
      return '';
  }
};

// 修改按钮点击方法
const handleReRun = async (item) => {
  if (!canReRun(item.state)) {
    showToast(getButtonDisabledTip('rerun', item.state));
    return;
  }
  try {
    await reRunProcessInstance(clusterId.value, projectCode.value, item.id);
    showToast('重新运行成功');
    onSearch();
  } catch (error) {
    console.error('重新运行失败:', error);
    showToast('重新运行失败');
  }
};

const handlePause = async (item) => {
  if (!canPause(item.state)) {
    showToast(getButtonDisabledTip('pause', item.state));
    return;
  }
  try {
    await pauseProcessInstance(clusterId.value, projectCode.value, item.id);
    showToast('暂停成功');
    onSearch();
  } catch (error) {
    console.error('暂停失败:', error);
    showToast('暂停失败');
  }
};

const handleStop = async (item) => {
  if (!canStop(item.state)) {
    showToast(getButtonDisabledTip('stop', item.state));
    return;
  }
  try {
    await stopProcessInstance(clusterId.value, projectCode.value, item.id);
    showToast('停止成功');
    onSearch();
  } catch (error) {
    console.error('停止失败:', error);
    showToast('停止失败');
  }
};

const handleDelete = async (item) => {
  if (!canDelete(item.state)) {
    showToast(getButtonDisabledTip('delete', item.state));
    return;
  }
  try {
    await deleteProcessInstance(clusterId.value, projectCode.value, item.id);
    showToast('删除成功');
    onSearch();
  } catch (error) {
    console.error('删除失败:', error);
    showToast('删除失败');
  }
};

const goToTaskList = (item) => {
  router.push({
    name: 'opsWorkflowTasks',
    params: {
      clusterId: clusterId.value,
      projectCode: projectCode.value,
      processInstanceId: item.id.toString(),
      processInstanceName: encodeURIComponent(item.name)
    }
  });
};

// 添加展开状态控制
const toggleExpand = (item) => {
  item.isExpanded = !item.isExpanded;
};

// 格式化时间的方法
const formatTime = (time) => {
  if (!time) return '- -';
  return new Date(time).toLocaleString();
};

// 格式化运行时长
const formatDuration = (duration) => {
  if (!duration || duration === 'NaN分NaN秒') return '- -';
  // 如果是 "9m 32s" 这样的格式
  if (typeof duration === 'string' && duration.includes('m')) {
    const [min, sec] = duration.split('m');
    return `${min}分${sec.replace('s', '')}秒`;
  }
  // 如果是数字（秒数）
  if (typeof duration === 'number') {
    const minutes = Math.floor(duration / 60);
    const seconds = duration % 60;
    return `${minutes}分${seconds}秒`;
  }
  return duration;
};

// 获取状态样式类
const getStateClass = (state) => {
  switch (state) {
    case 'RUNNING_EXECUTION':
      return 'state-running';
    case 'SUCCESS':
      return 'state-success';
    case 'FAILURE':
      return 'state-failed';
    case 'STOP':
      return 'state-stopped';
    case 'PAUSE':
      return 'state-paused';
    default:
      return 'state-default';
  }
};

// 添加时间验证方法
const validateDateFormat = (date) => {
  const regex = /^\d{4}-\d{2}-\d{2}$/;
  return regex.test(date);
};

// 添加刷新方法
const onRefresh = async () => {
  try {
    // 重置所有状态
    currentPage.value = 1;
    items.value = [];
    finished.value = false;
    loading.value = false;
    
    // 重新加载数据
    await onSearch();
  } finally {
    refreshing.value = false;
  }
};
</script>

<template>
<div class="page-container">
  <div class="search-bar">
    <div class="search-content">
      <!-- 搜索输入框 -->
      <div class="search-item">
        <van-search
          v-model="searchVal"
          placeholder="工作流实例名称"
          class="search-input"
          @search="onSearch"
        />
      </div>

      <!-- 状态选择 -->
      <div class="search-item">
        <van-dropdown-menu class="status-dropdown">
          <van-dropdown-item
            v-model="stateType"
            :options="stateOptions"
          >
            <template #title>
              <span>状态: {{ getStateText(stateType) }}</span>
            </template>
          </van-dropdown-item>
        </van-dropdown-menu>
      </div>

      <!-- 时间输入 -->
      <div class="search-item">
        <van-field
          v-model="startDate"
          label="开始日期"
          placeholder="YYYY-MM-DD"
          input-align="left"
        />
      </div>
      <div class="search-item">
        <van-field
          v-model="endDate"
          label="结束日期"
          placeholder="YYYY-MM-DD"
          input-align="left"
        />
      </div>

      <!-- 按钮组 -->
      <div class="button-group">
        <van-button type="primary" size="small" @click="onSearch">搜索</van-button>
        <van-button type="primary" size="small" @click="onReset">重置</van-button>
      </div>
    </div>
  </div>

  <!-- 添加下拉刷新组件 -->
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <div class="list-container">
      <!-- 添加首次加载的骨架屏 -->
      <div v-if="loading && items.length === 0" class="skeleton-list">
        <van-skeleton title :row="3" v-for="i in 3" :key="i" class="skeleton-item" />
      </div>

      <van-list
        v-else
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        error-text="加载失败，点击重试"
        :offset="300"
        :immediate-check="false"
        @load="onLoad"
      >
        <!-- 添加空状态显示 -->
        <van-empty
          v-if="!loading && items.length === 0"
          description="暂无工作流实例"
        />
        
        <!-- 列表内容 -->
        <van-cell-group
          v-for="item in items"
          :key="item.id"
          class="instance-card"
        >
          <!-- 主要信息显示 -->
          <van-cell
            :title="item.name"
            is-link
            @click="toggleExpand(item)"
          />

          <!-- 基础信息显示 -->
          <div class="basic-info">
            <div class="info-row">
              <span class="label">调度时间：</span>
              <span class="value">{{formatTime(item.scheduleTime)}}</span>
            </div>
            <div class="info-row">
              <span class="label">状态：</span>
              <span class="value" :class="getStateClass(item.state)">
                {{ getStateText(item.state) }}
              </span>
            </div>
          </div>

          <!-- 展开的详细信息 -->
          <div v-show="item.isExpanded" class="expand-content">
            <div class="info-grid">
              <div class="info-item">
                <span class="label">开始时间</span>
                <span class="value">{{formatTime(item.startTime)}}</span>
              </div>
              <div class="info-item">
                <span class="label">结束时间</span>
                <span class="value">{{formatTime(item.endTime)}}</span>
              </div>
              <div class="info-item">
                <span class="label">编号</span>
                <span class="value">{{item.id}}</span>
              </div>
              <div class="info-item">
                <span class="label">运行类型</span>
                <span class="value">{{item.commandType}}</span>
              </div>
              <div class="info-item">
                <span class="label">运行时长</span>
                <span class="value">{{formatDuration(item.duration || '')}}</span>
              </div>
              <div class="info-item">
                <span class="label">运行次数</span>
                <span class="value">{{item.runTimes}}</span>
              </div>
              <div class="info-item">
                <span class="label">执行用户</span>
                <span class="value">{{item.executorName || '- -'}}</span>
              </div>
            </div>

            <!-- 操作按钮组 -->
            <div class="action-buttons">
              <van-button
                round
                size="small"
                type="primary"
                :disabled="!canReRun(item.state)"
                @click.stop="handleReRun(item)"
                :title="getButtonDisabledTip('rerun', item.state)"
              >
                重新运行
              </van-button>
              
              <van-button
                round
                size="small"
                type="warning"
                :disabled="!canPause(item.state)"
                @click.stop="handlePause(item)"
                :title="getButtonDisabledTip('pause', item.state)"
              >
                暂停
              </van-button>
              
              <van-button
                round
                size="small"
                type="danger"
                :disabled="!canStop(item.state)"
                @click.stop="handleStop(item)"
                :title="getButtonDisabledTip('stop', item.state)"
              >
                停止
              </van-button>
              
              <van-button
                round
                size="small"
                type="warning"
                :disabled="!canDelete(item.state)"
                @click.stop="handleDelete(item)"
                :title="getButtonDisabledTip('delete', item.state)"
              >
                删除
              </van-button>
            </div>

            <!-- 查看任务按钮 -->
            <div class="view-tasks" @click="goToTaskList(item)">
              <van-cell
                title="查看任务列表"
                is-link
                center
              >
                <template #icon>
                  <van-icon name="bars" class="task-icon" />
                </template>
              </van-cell>
            </div>
          </div>
        </van-cell-group>
      </van-list>
    </div>
  </van-pull-refresh>
</div>
</template>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.search-bar {
  position: sticky;
  top: 0;
  z-index: 1;
  background: #fff;
  padding: 12px;
  border-bottom: 1px solid #eee;
}

.search-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.search-item {
  width: 100%;
}

.status-dropdown {
  width: 100%;
}

:deep(.van-dropdown-menu) {
  height: 36px;
  background: var(--van-field-background);
  border-radius: 2px;
}

:deep(.van-dropdown-menu__bar) {
  box-shadow: none;
  height: 36px;
}

:deep(.van-dropdown-menu__title) {
  font-size: 14px;
  line-height: 36px;
  padding: 0 8px;
  color: var(--van-text-color);
}

:deep(.van-dropdown-menu__title.van-dropdown-menu__title--active) {
  color: var(--van-primary-color);
}

:deep(.van-dropdown-item__option--active) {
  color: var(--van-primary-color);
}

:deep(.van-dropdown-item__option) {
  padding: 10px 12px;
  font-size: 14px;
}

.button-group {
  grid-column: span 2;
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 8px;
}

.list-container {
  flex: 1;
  overflow-y: auto;
  height: calc(100vh - 200px);
}

.instance-card {
  margin: 0;
  background: #fff;
}

.instance-card + .instance-card {
  border-top: 1px solid #eee;
}

/* 移除圆角和内边距 */
:deep(.van-cell-group--inset) {
  margin: 0;
  border-radius: 0;
}

/* 调整搜索框样式 */
:deep(.van-search) {
  padding: 8px 0;
}

/* 调整输入框样式 */
:deep(.van-field__control) {
  font-size: 14px;
}

.basic-info {
  padding: 8px 12px;
  font-size: 13px;
}

.info-row {
  display: flex;
  margin-bottom: 4px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  color: #666;
  width: 70px;
  flex-shrink: 0;
  font-size: 13px;
}

.value {
  flex: 1;
  font-size: 13px;
}

.expand-content {
  padding: 12px;
  background: #f8f8f8;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  margin-bottom: 12px;
  font-size: 13px;
}

.action-buttons {
  display: flex;
  gap: 6px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

:deep(.van-button--small) {
  font-size: 12px;
  padding: 0 10px;
}

.state-success { 
  color: #67c23a;  /* 成功-绿色 */
}
.state-running { 
  color: #409eff;  /* 运行中-蓝色 */
}
.state-failed { 
  color: #f56c6c;  /* 失败-红色 */
}
.state-stopped { 
  color: #909399;  /* 停止-灰色 */
}
.state-paused { 
  color: #e6a23c;  /* 暂停-橙色 */
}
.state-default { 
  color: #606266;  /* 默认-深灰色 */
}

/* 修改工作流实例名称的字体大小 */
:deep(.van-cell__title) {
  font-size: 14px;
  font-weight: normal;
}

.skeleton-list {
  padding: 16px;
}

.skeleton-item {
  margin-bottom: 16px;
  background: #fff;
  padding: 16px;
  border-radius: 8px;
}

/* 禁用按钮样式 */
.action-buttons .van-button--disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 按钮提示样式 */
.action-buttons .van-button {
  position: relative;
}

/* 添加按钮提示效果 */
.action-buttons .van-button--disabled:hover::before {
  content: attr(title);
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  padding: 4px 8px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  margin-bottom: 4px;
  z-index: 1;
}
</style>